package controllers

import (
	"encoding/json"
	"strconv"
	"supershare/backend/middleware"
	"supershare/backend/models"

	"github.com/beego/beego/v2/server/web"
)

// StoreTimeController 门店营业时间控制器
type StoreTimeController struct {
	web.Controller
}

// StoreTimeData 门店营业时间数据结构
type StoreTimeData struct {
	Day       int    `json:"day"`       // 星期几，1-7 代表周一到周日
	DayName   string `json:"dayName"`   // 星期名称
	IsOpen    bool   `json:"isOpen"`    // 是否营业
	OpenTime  string `json:"openTime"`  // 开始时间，格式：HH:MM
	CloseTime string `json:"closeTime"` // 结束时间，格式：HH:MM
}

// WorkdayTimeData 工作日营业时间数据结构
type WorkdayTimeData struct {
	IsOpen    bool   `json:"isOpen"`    // 是否营业
	OpenTime  string `json:"openTime"`  // 开始时间，格式：HH:MM
	CloseTime string `json:"closeTime"` // 结束时间，格式：HH:MM
}

// BusinessHoursData 营业时间复合数据结构
type BusinessHoursData struct {
	Workday WorkdayTimeData `json:"workday"` // 工作日营业时间
	Weekend WorkdayTimeData `json:"weekend"` // 周末营业时间
	Daily   []StoreTimeData `json:"daily"`   // 每日营业时间详情
}

// SaveStoreTimeRequest 保存门店营业时间请求
type SaveStoreTimeRequest struct {
	StoreId  int64              `json:"store_id"` // 门店ID
	TimeData *BusinessHoursData `json:"timeData"` // 营业时间数据
}

// GetStoreTime 获取门店营业时间
func (c *StoreTimeController) GetStoreTime() {
	// 获取门店ID
	id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
	if id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的门店ID",
		}
		c.ServeJSON()
		return
	}

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取门店信息
	store, err := models.GetStoreById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "门店不存在",
		}
		c.ServeJSON()
		return
	}

	// 检查权限（如果是加盟商管理员，只能查看自己的门店）
	if admin.FranchiseId > 0 && store.FranchiseId != admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权查看该门店信息",
		}
		c.ServeJSON()
		return
	}

	// 从BusinessHours字段获取营业时间数据
	var timeData *BusinessHoursData
	if store.BusinessHours != "" {
		// 尝试解析为新格式
		timeData = &BusinessHoursData{}
		err = json.Unmarshal([]byte(store.BusinessHours), timeData)
		if err != nil {
			// 如果解析为新格式失败，尝试解析为旧格式
			var oldTimeData []StoreTimeData
			err = json.Unmarshal([]byte(store.BusinessHours), &oldTimeData)
			if err != nil {
				// 如果解析失败，返回默认的营业时间数据
				timeData = getDefaultBusinessHoursData()
			} else {
				// 将旧格式转换为新格式
				timeData = convertToBusinessHoursData(oldTimeData)
			}
		}
	} else {
		// 如果没有设置营业时间，返回默认的营业时间数据
		timeData = getDefaultBusinessHoursData()
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取门店营业时间成功",
		"data":    timeData,
	}
	c.ServeJSON()
}

// SaveStoreTime 保存门店营业时间
func (c *StoreTimeController) SaveStoreTime() {
	// 解析请求参数
	var req SaveStoreTimeRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 验证门店ID
	if req.StoreId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的门店ID",
		}
		c.ServeJSON()
		return
	}

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取门店信息
	store, err := models.GetStoreById(req.StoreId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "门店不存在",
		}
		c.ServeJSON()
		return
	}

	// 检查权限（如果是加盟商管理员，只能修改自己的门店）
	if admin.FranchiseId > 0 && store.FranchiseId != admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权修改该门店信息",
		}
		c.ServeJSON()
		return
	}

	// 将营业时间数据转换为JSON字符串
	var timeDataJSON []byte
	if req.TimeData != nil {
		timeDataJSON, err = json.Marshal(req.TimeData)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "处理营业时间数据失败",
			}
			c.ServeJSON()
			return
		}
	} else {
		// 如果没有提供时间数据，使用默认数据
		defaultData := getDefaultBusinessHoursData()
		timeDataJSON, _ = json.Marshal(defaultData)
	}

	// 更新门店的BusinessHours字段
	store.BusinessHours = string(timeDataJSON)
	store.UpdatedBy = admin.Username
	store.BeforeUpdate()

	// 保存到数据库
	err = models.UpdateStore(store, "BusinessHours", "UpdatedBy", "UpdatedAt")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "保存门店营业时间失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "保存门店营业时间成功",
	}
	c.ServeJSON()
}

// getDefaultTimeData 获取默认的营业时间数据（旧格式）
func getDefaultTimeData() []StoreTimeData {
	weekdays := []string{"周一", "周二", "周三", "周四", "周五", "周六", "周日"}
	timeData := make([]StoreTimeData, 7)

	for i, day := range weekdays {
		timeData[i] = StoreTimeData{
			Day:       i + 1,
			DayName:   day,
			IsOpen:    true,
			OpenTime:  "00:00",
			CloseTime: "23:59",
		}
	}

	return timeData
}

// getDefaultBusinessHoursData 获取默认的营业时间数据（新格式）
func getDefaultBusinessHoursData() *BusinessHoursData {
	weekdays := []string{"周一", "周二", "周三", "周四", "周五", "周六", "周日"}
	dailyData := make([]StoreTimeData, 7)

	for i, day := range weekdays {
		dailyData[i] = StoreTimeData{
			Day:       i + 1,
			DayName:   day,
			IsOpen:    true,
			OpenTime:  "00:00",
			CloseTime: "23:59",
		}
	}

	return &BusinessHoursData{
		Workday: WorkdayTimeData{
			IsOpen:    true,
			OpenTime:  "00:00",
			CloseTime: "23:59",
		},
		Weekend: WorkdayTimeData{
			IsOpen:    true,
			OpenTime:  "00:00",
			CloseTime: "23:59",
		},
		Daily: dailyData,
	}
}

// convertToBusinessHoursData 将旧格式转换为新格式
func convertToBusinessHoursData(oldData []StoreTimeData) *BusinessHoursData {
	result := &BusinessHoursData{
		Daily: oldData,
	}

	// 从每日数据中提取工作日和周末的数据
	workdays := []StoreTimeData{}
	weekends := []StoreTimeData{}

	for _, item := range oldData {
		if item.Day >= 1 && item.Day <= 5 {
			workdays = append(workdays, item)
		} else if item.Day >= 6 && item.Day <= 7 {
			weekends = append(weekends, item)
		}
	}

	// 检查工作日是否统一
	workdayOpenTimes := map[string]bool{}
	workdayCloseTimes := map[string]bool{}
	workdayIsOpen := map[bool]bool{}

	for _, item := range workdays {
		workdayOpenTimes[item.OpenTime] = true
		workdayCloseTimes[item.CloseTime] = true
		workdayIsOpen[item.IsOpen] = true
	}

	// 检查周末是否统一
	weekendOpenTimes := map[string]bool{}
	weekendCloseTimes := map[string]bool{}
	weekendIsOpen := map[bool]bool{}

	for _, item := range weekends {
		weekendOpenTimes[item.OpenTime] = true
		weekendCloseTimes[item.CloseTime] = true
		weekendIsOpen[item.IsOpen] = true
	}

	// 设置工作日数据
	if len(workdays) > 0 {
		if len(workdayOpenTimes) == 1 && len(workdayCloseTimes) == 1 && len(workdayIsOpen) == 1 {
			// 如果工作日设置统一，使用第一个工作日的设置
			result.Workday = WorkdayTimeData{
				IsOpen:    workdays[0].IsOpen,
				OpenTime:  workdays[0].OpenTime,
				CloseTime: workdays[0].CloseTime,
			}
		} else {
			// 如果工作日设置不统一，使用默认设置
			result.Workday = WorkdayTimeData{
				IsOpen:    true,
				OpenTime:  "00:00",
				CloseTime: "23:59",
			}
		}
	}

	// 设置周末数据
	if len(weekends) > 0 {
		if len(weekendOpenTimes) == 1 && len(weekendCloseTimes) == 1 && len(weekendIsOpen) == 1 {
			// 如果周末设置统一，使用第一个周末的设置
			result.Weekend = WorkdayTimeData{
				IsOpen:    weekends[0].IsOpen,
				OpenTime:  weekends[0].OpenTime,
				CloseTime: weekends[0].CloseTime,
			}
		} else {
			// 如果周末设置不统一，使用默认设置
			result.Weekend = WorkdayTimeData{
				IsOpen:    true,
				OpenTime:  "00:00",
				CloseTime: "23:59",
			}
		}
	}

	return result
}
